﻿package com.badibadi.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.badibadi.adapter.AddingRecordNewAdapter;
import com.badibadi.infos.BeginFirstRecord;
import com.badibadi.infos.ListsModel;
import com.badibadi.infos.Record_array;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.ImageTools;
import com.badibadi.mytools.InterestModel;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MySharePreferences;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.SelectPicLayoutActivity;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.XUtils;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.test.UiThreadTest;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

//fqcjlcyyjtpx record_new_up_pic record_new_img record_new_up_pic record_new_img record_new_radio1 上传信息为空 beginFistRecord beginFistRecord
public class AddingRecordNewActivity extends BaseActivity implements // fqcjlcyyjtpx
		OnClickListener {
	private GridView gv;
	private AddingRecordNewAdapter arnAdapter;
	private Button clear_text;
	protected EditText et0;
	public Map<Integer, String> TitleMap;
	// TitleMap的大小
	public int Size;// 更新TitleMap的时候一定要更新它
	/** 上传图片的文字 */
	private TextView up_pic;
	public Spinner quanxian;
	public RadioGroup group_toupiao;
	public RadioButton radio0, radio1;

	private String uid;
	private String cid;
	/** 封装的提交的类 **/
	private BeginFirstRecord beginFirstRecord;

	private static final int TAKE_PICTURE = 0;
	private static final int CHOOSE_PICTURE = 1;
	private static final int CROP = 2;
	private static final int CROP_PICTURE = 3;

	private static final int SCALE = 5;// 照片缩小比例
	public ImageView iv_image = null;
	// 需要金币数beginFistRecord
	private int money = 0;

	private List<InterestModel> Interestlist;
	private TextView fqcj;
	private String[] QQxian;
	private ArrayAdapter<String> adapter;
	private List<String> allCountries;
	private DisplayImageOptions options;// record_new_back\
	private ListsModel listsModel;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(AddingRecordNewActivity.this);
				try {
					Utils.showMessage(AddingRecordNewActivity.this,
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:

				try {
					Utils.ExitPrgress(AddingRecordNewActivity.this);
					initGridView();
				} catch (Exception e) {
					// TODO: handle exception
				}
				// arnAdapter.notifyDataSetChanged();
				break;
			case 3:
				try {
					Utils.ExitPrgress(AddingRecordNewActivity.this);
					Utils.showMessage(AddingRecordNewActivity.this,
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2000:

				try {
					Utils.ExitProgress_hen(AddingRecordNewActivity.this);
					Utils.ExitPrgress(AddingRecordNewActivity.this);
					ImageLoader.getInstance().displayImage(
							Constants.BadiDownImgUrl + "/"
									+ msg.getData().getString("path")
									+ Constants.Appactivitycover, iv_image,
							options);

					Utils.showMessage(AddingRecordNewActivity.this,
							getResources().getString(R.string.l_xb18));
					beginFirstRecord.setPic(msg.getData().getString("path"));
//					System.out
//							.println("服务器的图片地址是:" + beginFirstRecord.getPic());
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		// android4Detail();
		setContentView(R.layout.record_new);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		try {
			cid = getIntent().getStringExtra("cid");
		} catch (Exception e) {
			// TODO: handle exception
		}
		uid = Utils.getUid(AddingRecordNewActivity.this);
		// uid = new MySharePreferences(this, "user").get("uid", "");
		init();
		all_record_type();
	}

	private void init() {
		// TODO Auto-generated method stub
		QQxian = new String[] { getResources().getString(R.string.l_xb30),
				getResources().getString(R.string.AllThePeople) };

		fqcj = (TextView) this.findViewById(R.id.fqcjlcyyjtpx);
		Interestlist = new ArrayList<InterestModel>();
		// String text = String.format(
		// getResources().getString(R.string.fqcjlcyyjtpx), money);
		// SpannableStringBuilder style = new SpannableStringBuilder(text);
		// // 设置指定位置文字的颜色
		// style.setSpan(new ForegroundColorSpan(Color.BLUE), 10,
		// (10 + ("" + money).length()),
		// Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		// fqcj.setText(style);
		clear_text = (Button) this
				.findViewById(R.id.AddingRecord_New_Clear_text);
		et0 = (EditText) this.findViewById(R.id.AddingRecord_New_text0);
		clear_text.setOnClickListener(AddingRecordNewActivity.this);
		up_pic = (TextView) this.findViewById(R.id.record_new_up_pic);
		up_pic.setOnClickListener(AddingRecordNewActivity.this);
		iv_image = (ImageView) this.findViewById(R.id.record_new_img);
		iv_image.setOnClickListener(AddingRecordNewActivity.this);
		// iv_image.getBackground();
		group_toupiao = (RadioGroup) this.findViewById(R.id.group_toupiao);
		radio0 = (RadioButton) this.findViewById(R.id.record_new_radio0);
		radio1 = (RadioButton) this.findViewById(R.id.record_new_radio1);
		quanxian = (Spinner) this.findViewById(R.id.record_new_quanxian);
		if (cid != null) {
			allCountries = new ArrayList<String>();
			for (int i = 0; i < QQxian.length; i++) {
				allCountries.add(QQxian[i]);
			}
			adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_item, allCountries);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			quanxian.setAdapter(adapter);
		}
		this.findViewById(R.id.beginFistRecord).setOnClickListener(this);
		this.findViewById(R.id.record_new_back).setOnClickListener(this);
		this.findViewById(R.id.record_new_uppic_settings).setOnClickListener(
				this);
		beginFirstRecord = new BeginFirstRecord();
		beginFirstRecord.setQuanxian("1");
		quanxian.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (cid != null) {
					switch (arg2) {
					case 0:
						beginFirstRecord.setQuanxian("0");
						break;
					case 1:
						beginFirstRecord.setQuanxian("1");

						break;
					default:
						beginFirstRecord.setQuanxian("0");
						break;
					}
				} else {
					switch (arg2) {
					case 0:
						beginFirstRecord.setQuanxian("1");
						// Toast.makeText(getApplicationContext(), "1",
						// 0).show();
						break;
					case 1:
						beginFirstRecord.setQuanxian("2");
						// Toast.makeText(getApplicationContext(), "2",
						// 0).show();
						break;
					case 2:
						beginFirstRecord.setQuanxian("0");
						// Toast.makeText(getApplicationContext(), "0",
						// 0).show();
						break;
					default:
						beginFirstRecord.setQuanxian("0");
						break;
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		beginFirstRecord.setIsTouPiao("2");

		group_toupiao.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				if (arg1 == radio0.getId()) {
					beginFirstRecord.setIsTouPiao("1");
				} else if (arg1 == radio1.getId()) {
					beginFirstRecord.setIsTouPiao("2");
				}
			}
		});
	}

	/**
	 * 这里是gridVe
	 */
	protected void initGridView() {
		// TODO Auto-generated method stub
		if (listsModel.getLists() != null && !listsModel.getLists().isEmpty()) {
			Interestlist.clear();
			Interestlist.addAll(listsModel.getLists());
		}
		gv = (GridView) findViewById(R.id.adding_record_new_label_type_gridView1);
		arnAdapter = new AddingRecordNewAdapter(AddingRecordNewActivity.this,
				Interestlist);
		TitleMap = new Hashtable<Integer, String>();
		// if (Interestlist != null && Interestlist.size() > 0) {
		// money = Integer.valueOf(Interestlist.get(0).getGold());
		// } else {
		// money = 0;
		// }
		if (!StringUtil.isNullOrEmpty(listsModel.getNeedGold())) {
			money = Integer.valueOf(listsModel.getNeedGold());
		} else {
			money = 0;
		}
		String text = String.format(
				getResources().getString(R.string.fqcjlcyyjtpx), money);
		// if(text.in)
		int index = text.indexOf("" + money);

		SpannableStringBuilder style = new SpannableStringBuilder(text);
		// 设置指定位置文字的颜色
		style.setSpan(new ForegroundColorSpan(Color.BLUE), index,
				(index + ("" + money).length()),
				Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		fqcj.setText(style);
		gv.setAdapter(arnAdapter);
		gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (arnAdapter.getIsItemClick(position) == true) {
					arnAdapter.setIsItemClick(position);
					arnAdapter.notifyDataSetInvalidated();
				} else if (arnAdapter.getSelectNumber() >= arnAdapter
						.getUpperLimit()) {
					ShowToast(AddingRecordNewActivity.this,
							getResources().getString(R.string.l_xb31)
									+ arnAdapter.getUpperLimit()
									+ getResources().getString(R.string.l_xb5));
				} else {
					// ShowToast(AddingRecordNewActivity.this, "你点击了" +
					// position);
					arnAdapter.setIsItemClick(position);
					arnAdapter.notifyDataSetInvalidated();
				}
				// 在提交按钮将TitleMap提交
				TitleMap = arnAdapter.getTitleMap();
				Size = arnAdapter.getMapSize();
				// Iterator it=TitleMap.entrySet().iterator();
				// while(it.hasNext())
				// {
				// Map.Entry entry=(Map.Entry)it.next();
				// Object key=entry.getKey();
				// Object value=entry.getValue();
				//    
				// }
			}
		});
		// if (Interestlist != null && Interestlist.size() > 0) {
		if (Integer.valueOf(listsModel.getNeedGold()) > Integer
				.valueOf(listsModel.getUserGold())) {
//			   
//					"进入" + listsModel.getNeedGold() + "   "
//							+ listsModel.getUserGold());
			radio0.setEnabled(false);
			// group_toupiao.setFocusableInTouchMode(false);
		}

		// }
		// add();
		// ViewGroup.LayoutParams vl=new
		// ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
		// ViewGroup.LayoutParams.WRAP_CONTENT);
		// gv.setLayoutParams(vl);

	}

	// public void add() {
	//
	// }

	// public class Utility {
	// public void setListViewHeightBasedOnChildren(ListView listView) {
	// // 获取ListView对应的Adapter
	// ListAdapter listAdapter = listView.getAdapter();
	// if (listAdapter == null) {
	// return;
	// }
	//
	// int totalHeight = 0;
	// for (int i = 0, len = listAdapter.getCount(); i < len; i++) { //
	// listAdapter.getCount()返回数据项的数目
	// View listItem = listAdapter.getView(i, null, listView);
	// listItem.measure(0, 0); // 计算子项View 的宽高
	// totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
	// }
	//
	// ViewGroup.LayoutParams params = listView.getLayoutParams();
	// params.height = totalHeight
	// + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
	// // listView.getDividerHeight()获取子项间分隔符占用的高度
	// // params.height最后得到整个ListView完整显示需要的高度
	// listView.setLayoutParams(params);
	// }
	// }

	private void all_record_type() {
		Utils.showPrgress(AddingRecordNewActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				listsModel = new ListsModel();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("languageType", Dialog
						.getSystemLanguageType(AddingRecordNewActivity.this));
				map.put("uid", Utils.getUid(AddingRecordNewActivity.this));
				map.put("type", "jilu");
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "type/listType");
				
				if (content != null) {
					//    ("结果是:" + content);
					Results results = Utils.checkResult_NNN(
							getApplicationContext(), content);
					if (results != null && results.getRetmsg() != null) {
						//    
//						   ("得到的结果是：" + results.getRetmsg());
						try {
							listsModel = JSONUtils.getEntityByJsonString(
									results.getRetmsg(), ListsModel.class);
							System.out.println("all_record_type"+results.getRetmsg());
							handler.sendEmptyMessage(2);
						} catch (JSONException e) {
							//    ("解析出错");
							   
						} catch (Exception e) {
							// TODO Auto-generated catch block
//							   
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.AddingRecord_New_Clear_text:
			et0.setText("");
			break;
		case R.id.record_new_up_pic:
			// 截图后显示
			// showPicturePicker(AddingRecordNewActivity.this, true);
			intent = new Intent(AddingRecordNewActivity.this,
					SelectPicLayoutActivity.class);
			intent.putExtra("Cutting", "yes");// 传入是否需要裁剪的参数，传则不需要，不传则需要
			startActivityForResult(intent, 0);
			break;
		case R.id.record_new_img:
			intent = new Intent(AddingRecordNewActivity.this,
					SelectPicLayoutActivity.class);
			intent.putExtra("Cutting", "yes");// 传入是否需要裁剪的参数，传则不需要，不传则需要
			startActivityForResult(intent, 0);
			break;
		// case R.id.img:
		// // 截图后显示
		// // showPicturePicker(AddingRecordNewActivity.this, true);
		// intent = new Intent(AddingRecordNewActivity.this,
		// SelectPicLayoutActivity.class);
		// intent.putExtra("Cutting", "yes");//传入是否需要裁剪的参数，传则不需要，不传则需要
		// startActivityForResult(intent, 0);
		// break;
		case R.id.beginFistRecord:
			// 没写完，在这里提交
			TiJiao();
			if (beginFirstRecord.getName() != null) {
				if (!beginFirstRecord.getMap().isEmpty()) {
					if (beginFirstRecord.getIsTouPiao() != null
							&& beginFirstRecord.getPic() != null
							&& beginFirstRecord.getQuanxian() != null) {
						try {
							// Constants.array_record = Tijiao_Json();
							Record_array array = new Record_array();

							array.setArray_record(Tijiao_Json().toString());
							intent = new Intent(AddingRecordNewActivity.this,
									AddingRecordFirstActivity.class);
							if (cid != null) {
								intent.putExtra("cid", cid);
							}
							intent.putExtra("array", array);
//							   
							intent.putExtra("is_newcreate", "yes");
							startActivity(intent);
							this.finish();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						Toast.makeText(getApplicationContext(),
								getResources().getString(R.string.l_xb26), 0)
								.show();
					}
				} else {
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.l_xb32), 0)
							.show();
				}
			} else {
				Toast.makeText(getApplicationContext(),
						getResources().getString(R.string.l_xb33), 0).show();
			}
			break;
		case R.id.record_new_back:
			this.finish();
			break;
		case R.id.record_new_uppic_settings:
			TiJiao();
			if (beginFirstRecord.getName() != null) {
				if (!beginFirstRecord.getMap().isEmpty()) {
					if (beginFirstRecord.getIsTouPiao() != null
							&& beginFirstRecord.getPic() != null
							&& beginFirstRecord.getQuanxian() != null) {
						try {
							Record_array array = new Record_array();
							// Constants.array_record = Tijiao_Json();
							array.setArray_record(Tijiao_Json().toString());
							intent = new Intent(AddingRecordNewActivity.this,
									AddingRecordFirstActivity.class);
							if (cid != null) {
								intent.putExtra("cid", cid);
							}
							intent.putExtra("array", array);
//							   
							intent.putExtra("is_newcreate", "yes");
							startActivity(intent);
							this.finish();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						Toast.makeText(getApplicationContext(),
								getResources().getString(R.string.l_xb26), 0)
								.show();
					}
				} else {
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.l_xb32), 0)
							.show();
				}
			} else {
				Toast.makeText(getApplicationContext(),
						getResources().getString(R.string.l_xb33), 0).show();
			}
			break;
		}
	}

	public void TiJiao() {
		// TODO Auto-generated method stub
		beginFirstRecord.setName(et0.getText().toString().trim());
		//    
		// beginFirstRecord.pic=ImageTools.loadBitmapFromView(AddingRecordNewActivity.this,
		// iv_image);
		//    
		// beginFirstRecord.quanxian = quanxian.getSelectedItem().toString();

		//    
		// beginFirstRecord.quanxian);
		// RadioButton rb = (RadioButton) this.findViewById(group_toupiao
		// .getCheckedRadioButtonId());
		// beginFirstRecord.isTouPiao = rb.getText().toString().trim();
		//    
		// + beginFirstRecord.isTouPiao);
		beginFirstRecord.setMoney(Integer.parseInt("" + money));
		//    
		beginFirstRecord.setMap(TitleMap);
		//    
	}

	private JSONObject Tijiao_Json() throws JSONException {
		String typid = "";
		// JSONArray array = new JSONArray();
		JSONObject object = new JSONObject();
		object.put("uid", uid);
		object.put("title", beginFirstRecord.getName());
		if (cid != null) {
			object.put("club_id", cid);
		}
		object.put("image", beginFirstRecord.getPic());
		if (cid != null) {
			object.put("c_status", beginFirstRecord.getQuanxian());
		} else {
			object.put("p_status", beginFirstRecord.getQuanxian());
		}
		object.put("is_vote", beginFirstRecord.getIsTouPiao());
		//    ("类型id" + beginFirstRecord.Map.toString());
		if (beginFirstRecord.getMap() != null
				&& !beginFirstRecord.getMap().isEmpty()) {
			for (int i = 0; i < Size; i++) {
				if (beginFirstRecord.getMap().get(i) != null) {
					typid += beginFirstRecord.getMap().get(i) + ",";
				}
			}
			object.put("type_id", typid.substring(0, typid.length() - 1));
		}
		// array.put(object);
		//    ("封装的数据是:" + array.toString());
		return object;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case TAKE_PICTURE:
				//    
				// // 将保存在本地的图片取出并缩小后显示在界面上
				// Bitmap bitmap = BitmapFactory.decodeFile(Environment
				// .getExternalStorageDirectory() + "/image.jpg");
				// Bitmap newBitmap = ImageTools.zoomBitmap(bitmap,
				// bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
				// // 由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
				// bitmap.recycle();
				// // 将处理过的图片显示在界面上，并保存到本地
				// iv_image.setImageBitmap(newBitmap);
				// ImageTools.savePhotoToSDCard(newBitmap, Environment
				// .getExternalStorageDirectory().getAbsolutePath(),
				// String.valueOf(System.currentTimeMillis()));
				if (resultCode == Activity.RESULT_OK) {
					String picPath = data
							.getStringExtra(SelectPicLayoutActivity.KEY_PHOTO_PATH);
					//    ("图片地址是:" + picPath);
					Bitmap bitmap = BitmapFactory.decodeFile(picPath);
					Bitmap newBitmap = ImageTools.zoomBitmap(bitmap,
							bitmap.getWidth() / SCALE, bitmap.getHeight()
									/ SCALE);
//					   
//							+ bitmap.getHeight() / SCALE);
					// 由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
					bitmap.recycle();
					// 将处理过的图片显示在界面上，并保存到本地
					// iv_image.setImageBitmap(newBitmap);
					// userDataSet.UserDataSet2(userInfoModel, 2, picPath,
					// true);
					XUtils.UpImg(picPath, AddingRecordNewActivity.this, handler);
				}
				break;
			case CHOOSE_PICTURE:
//				   
				ContentResolver resolver = getContentResolver();
				// 照片的原始资源地址
				Uri originalUri = data.getData();
				try {
					// 使用ContentProvider通过URI获取原始图片
					Bitmap photo = MediaStore.Images.Media.getBitmap(resolver,
							originalUri);
					if (photo != null) {
						// 为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
						Bitmap smallBitmap = ImageTools.zoomBitmap(photo,
								photo.getWidth() / SCALE, photo.getHeight()
										/ SCALE);
						// 释放原始图片占用的内存，防止out of memory异常发生
						photo.recycle();

						iv_image.setImageBitmap(smallBitmap);
					}
				} catch (FileNotFoundException e) {
					   
				} catch (IOException e) {
					   
				}
				break;

			case CROP:
//				   
				Uri uri = null;
				if (data != null) {
					uri = data.getData();
//					   ("Data");
				} else {
//					   ("File");
					String fileName = getSharedPreferences("temp",
							Context.MODE_WORLD_WRITEABLE).getString("tempName",
							"");
					uri = Uri.fromFile(new File(Environment
							.getExternalStorageDirectory(), fileName));
				}
				cropImage(uri, 300, 300, CROP_PICTURE);
				break;

			case CROP_PICTURE:
//				   
				Bitmap photo = null;
				Uri photoUri = data.getData();
				if (photoUri != null) {
					photo = BitmapFactory.decodeFile(photoUri.getPath());
				}
				if (photo == null) {
					Bundle extra = data.getExtras();
					if (extra != null) {
						photo = (Bitmap) extra.get("data");
						ByteArrayOutputStream stream = new ByteArrayOutputStream();
						photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
					}
				}
				iv_image.setImageBitmap(photo);
				break;
			default:
				break;
			}
		}
	}

	public void showPicturePicker(Context context, boolean isCrop) {
		final boolean crop = isCrop;
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(getResources().getString(R.string.l_xb34));
		builder.setNegativeButton(getResources().getString(R.string.cancel),
				null);
		builder.setItems(
				new String[] { getResources().getString(R.string.l_xb35),
						getResources().getString(R.string.l_xb36) },
				new DialogInterface.OnClickListener() {
					// 类型码
					int REQUEST_CODE;

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case TAKE_PICTURE:
							Uri imageUri = null;
							String fileName = null;
							Intent openCameraIntent = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							if (crop) {
								REQUEST_CODE = CROP;
								// 删除上一次截图的临时文件
								SharedPreferences sharedPreferences = getSharedPreferences(
										"temp", Context.MODE_WORLD_WRITEABLE);
								ImageTools.deletePhotoAtPathAndName(Environment
										.getExternalStorageDirectory()
										.getAbsolutePath(), sharedPreferences
										.getString("tempName", ""));

								// 保存本次截图临时文件名字
								fileName = String.valueOf(System
										.currentTimeMillis()) + ".jpg";
								Editor editor = sharedPreferences.edit();
								editor.putString("tempName", fileName);
								editor.commit();
							} else {
								REQUEST_CODE = TAKE_PICTURE;
								fileName = "image.jpg";
							}
							imageUri = Uri.fromFile(new File(Environment
									.getExternalStorageDirectory(), fileName));
							// 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
							openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
									imageUri);
							startActivityForResult(openCameraIntent,
									REQUEST_CODE);
							break;

						case CHOOSE_PICTURE:
							Intent openAlbumIntent = new Intent(
									Intent.ACTION_GET_CONTENT);
							if (crop) {
								REQUEST_CODE = CROP;
							} else {
								REQUEST_CODE = CHOOSE_PICTURE;
							}
							openAlbumIntent
									.setDataAndType(
											MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
											"image/*");
							startActivityForResult(openAlbumIntent,
									REQUEST_CODE);
							break;

						default:
							break;
						}
					}
				});
		builder.create().show();
	}

	// 截取图片
	public void cropImage(Uri uri, int outputX, int outputY, int requestCode) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("return-data", true);
		// String timeString;
		// Date date = new Date(System.currentTimeMillis());
		// SimpleDateFormat dateFormat = new SimpleDateFormat(
		// "'IMG'_yyyyMMddHHmmss");
		// timeString = dateFormat.format(date);
		// intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
		// Environment.getExternalStorageDirectory() + "/DCIM/Camera",
		// timeString + ".jpg")));
		startActivityForResult(intent, requestCode);
	}

	public Map<Integer, String> getTitleMap() {
		return TitleMap;
	}

	public void setTitleMap(Map<Integer, String> titleMap) {
		TitleMap = titleMap;
	}

	public AddingRecordNewAdapter getArnAdapter() {
		return arnAdapter;
	}

	public void setArnAdapter(AddingRecordNewAdapter arnAdapter) {
		this.arnAdapter = arnAdapter;
	}

	public BeginFirstRecord getBeginFirstRecord() {
		return beginFirstRecord;
	}

	public void setBeginFirstRecord(BeginFirstRecord beginFirstRecord) {
		this.beginFirstRecord = beginFirstRecord;
	}

}
